<?php
    /**
     * Created by PhpStorm.
     * 版权所有: 2019~2022 [ hhygyl ]
     * Date: 2019/6/27-15:04
     * Link: http://luckyadmin.luckyhhy.cn
     * FileName: Menu.php
     * Keys: ctrl+alt+L/ctrl+s(代码格式化) ctrl+J(代码提示) ctrl+R(替换)ALT+INSERT(生成代码(如GET,SET方法,构造函数等) , 光标在类中才生效)
     * CTRL+ALT+O (优化导入的类和包 需要配置) SHIFT+F2(高亮错误或警告快速定位错误)
     * CTRL+SHIFT+Z(代码向前) CTRL+SHIFT+/ (块状注释) ctrl+shift+enter(智能完善代码 如if())
     **************************************************************
     *                                                            *
     *   .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *
     *    |                     ______                     |      *
     *    |                  .-"      "-.                  |      *
     *    |                 /            \                 |      *
     *    |     _          |              |          _     |      *
     *    |    ( \         |,  .-.  .-.  ,|         / )    |      *
     *    |     > "=._     | )(__/  \__)( |     _.=" <     |      *
     *    |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
     *    |           "=._"(_     ^^     _)"_.="           |      *
     *    |               "=\__|IIIIII|__/="               |      *
     *    |              _.="| \IIIIII/ |"=._              |      *
     *    |    _     _.="_.="\          /"=._"=._     _    |      *
     *    |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *
     *    |    > _.="                            "=._ <    |      *
     *    |   (_/                                    \_)   |      *
     *    |                                                |      *
     *    '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
     *                                                            *
     *                    JUST FIND YOUR BUG !                    *
     **************************************************************
     */

    namespace app\admin\controller;

    use service\JsonService;
    use service\StringService;
    use service\TreeService;
    use service\UtilService;
    use think\Exception;


    class Adminmenu extends SystemBase
    {

        protected $menu;

        protected function _initialize()
        {
            parent::_initialize(); // TODO: Change the autogenerated stub
            $this->menu = new \app\admin\model\AdminMenu();//加载模型
        }



        /**
         * @return mixed|void
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: index
         * @describe: 菜单页显示
         */
        public function index()
        {
            if($this->request->isAjax()) {
                $where = [];
                $title = input("get.title") ? input("get.title") : "";
                //菜单名称
                if(!empty($title)) {
                    $where['title'] = ['like', "%$title%"];
                }
                return GetPageData($where, "admin_menu", "listorder asc", 2);
            }

            return $this->fetch();
        }



        /**
         * @return mixed
         * @author: hhygyl
         * @name: AddMenu
         * @describe 添加菜单
         */
        public function AddMenu()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();

                $res = $this->menu->addEditData($data);
                if($res['code']==1) {
                    if(isset($data['id'])){
                        $this->AddLogs('添加后台菜单');
                    }else{
                        $this->AddLogs('编辑后台菜单【'.$data['title'].'】');
                    }
                    $this->success("操作成功");
                }
                else {
                    $this->error($res['msg']);
                }

            }
            $tree = TreeService::toFormatTree($this->menu->GetMenuList());//获取菜单列表
            //dump($tree);die;
            $pid = $this->request->param("id/d");//父id

            $this->assign(compact("pid", "tree"));

            return $this->fetch();
        }


        /**
         * @return mixed
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: EditMenu
         * @describe:编辑菜单
         */
        public function EditMenu()
        {
            $tree = TreeService::toFormatTree($this->menu->GetMenuList());//获取菜单列表
            //dump($tree);die;
            $id   = $this->request->param("id/d");//父id
            $info = $this->menu->get($id)->toArray();
            $pid  = $info['pid'];

            //dump($pid);
            $this->assign(compact("pid", "tree", "info"));

            return $this->fetch();
        }


        /**
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: delete
         * @describe:批量或者单个删除
         */
        public function delete()
        {
            if($this->request->isAjax()) {
                $ids = $this->request->post("ids");
                try {
                    $res = $this->menu->del($ids);
                    if($res) {

                        $this->AddLogs('删除后台菜单');

                        $this->success("删除成功");
                    }
                    else {
                        $this->error("删除失败");
                    }
                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }
            }
        }



        /**
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: MenuListJson
         * @describe:根据权限返回菜单数据
         */
        public function MenuListJson()
        {
            if($this->request->isAjax()) {

                $role_id = self::$admin_info['role_id'];

                if((int)$role_id==1){ //超级管理员拥有所有权限
                    $all  = $this->menu->GetMenuList();
                    $this->success("", "", TreeService::DeepTree($all));
                    exit;
                }

                isset($role_id) ? $role_id : 0;
                $role  = new \app\admin\model\AdminRole();//实例化角色模型
                $child = TreeService::getChildrenPid($role->GetRoleList(), $role_id); //获取该角色的子集+

                if(empty($child)) {
                    //无子集
                    $res = db("admin_role")->where("id", $role_id)->value("rule"); //获取单个 权限数据
                    if(empty($res)) {
                        $this->error("无授权菜单");
                    }
                    else {
                        $rule = StringService::string2array($res);
                        $all  = $this->menu->GetMenuList(["id" => ["in", $rule]]);
                        $this->success("", "", TreeService::DeepTree($all));
                    }

                }
                else {
                    array_push($child, $role_id); //追加管理员角色id
                    $resd = db("admin_role")->where(["id" => ["in", $child], "status" => 1])->select();//获取所有
                    $node = [];
                    foreach($resd as $k => $v){
                        if(!empty($v['rule'])) {
                            $node[$k] = StringService::string2array($v['rule']);
                        }
                    }

                    if(empty($node)) {
                        $this->error("无授权菜单");
                    }
                    else {
                        $str = "";
                        foreach($node as $k => $v){
                            $str .= @implode(",", $v).",";
                        }
                        $ids  = @explode(",", $str);
                        $idsf = array_unique(array_filter($ids)); //去空去重
                        $all  = $this->menu->GetMenuList(["id" => ["in", $idsf]]);
                        unset($node);
                        $this->success("", "", TreeService::DeepTree($all));
                    }
                }


            }

        }



    }